package com.cloudservice.ccs.controller;

import com.cloudservice.ccs.biz.ICommonWordBiz;
import com.cloudservice.ccs.entity.CommonWord;
import com.cloudservice.ccs.model.ApiResult;
import com.cloudservice.ccs.model.PageData;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/common-word")
public class CommonWordController {
    @Autowired
    private ICommonWordBiz commonWordBiz;

    @PostMapping("/")
    public ApiResult save(@RequestBody CommonWord commonWord) {
        // 接口问题待讨论：是否应当返回生成的 id？
        //添加分类时带有的信息：lib,type，无需判断二者，仅相同时内容不同即可
        //添加常用语需要的信息：lib,type,content
        //这样写也兼容了相同的库重复添加type,会把重复的type（内容为空的）删除
        List<CommonWord> result = commonWordBiz.getAll();
        for(CommonWord commonWord1:result){
            if(commonWord1.getContent()==null&&commonWord1.getType().equals(commonWord.getType())&&commonWord1.getLib().equals(commonWord.getLib())){
                commonWordBiz.delete(commonWord1.getId());
            }
        }//等它主动退出来，删去所有重复添加的type但内容为空的记录
        commonWordBiz.save(commonWord);
        return ApiResult.success();
    }
    @PutMapping("/{id}")
    public ApiResult update(@PathVariable Integer id, @RequestBody CommonWord commonWord) {
        commonWordBiz.update(id, commonWord);
        CommonWord result = commonWordBiz.getOne(id);
        return ApiResult.successWithData(result);
    }

    @DeleteMapping("/{id}")
    public ApiResult delete(@PathVariable Integer id) {
        commonWordBiz.delete(id);
        return ApiResult.success();
    }

    // @RequiresPermissions("all")
    @PutMapping("/{id}/partial")
    public ApiResult partialUpdate(@PathVariable Integer id, @RequestBody Map<String, Object> fields) {
        commonWordBiz.partialUpdate(id, fields);
        CommonWord result = commonWordBiz.getOne(id);
        return ApiResult.successWithData(result);
    }

    @GetMapping("/{id}")
    public ApiResult queryById(@PathVariable Integer id) {
        CommonWord result = commonWordBiz.getOne(id);
        return ApiResult.successWithData(result);
    }

    @GetMapping("/")
    public ApiResult queryAll(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "0") Integer limit) {
        PageHelper.startPage(page, limit);
        List<CommonWord> result = commonWordBiz.getAll();
        return ApiResult.successWithData(PageData.fromPage((Page<CommonWord>) result));
    }
}
